package org.wmq.taskschedule.controller;

import lombok.extern.slf4j.Slf4j;
import org.opencv.core.Mat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.wmq.taskschedule.biz.model.DO.Param;
import org.wmq.taskschedule.biz.model.DO.Step;
import org.wmq.taskschedule.biz.model.DO.Task;
import org.wmq.taskschedule.biz.model.DTO.TaskCreateDTO;
import org.wmq.taskschedule.biz.model.VO.AlgorithmVO;
import org.wmq.taskschedule.common.AlgorithmTypeEnum;
import org.wmq.taskschedule.common.Result;
import org.wmq.taskschedule.config.ApplicationConfiguration;
import org.wmq.taskschedule.factory.AlgorithmStrategyFactory;
import org.wmq.taskschedule.service.StepService;
import org.wmq.taskschedule.service.TaskService;
import org.wmq.taskschedule.util.MinioService;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/task")
@Slf4j
public class TaskController {
    @Autowired
    private ApplicationConfiguration applicationConfiguration;
    @Autowired
    private TaskService taskService;
    @Autowired
    private StepService stepService;
    @Autowired
    private MinioService minioService;

    @GetMapping("/execute/{id}")
    public Result<Mat> execute(@PathVariable Long id) throws Exception {
        Task task = this.taskService.getById(id);
        int status = task.getStatus();
        if (status == Task.RUNNING) {
            log.error("任务正在运行中");
            return Result.error("任务正在运行中");
        }else if(status == Task.FINISHED){
            log.error("任务已结束");
            return Result.error("任务已结束");
        }else if(status == Task.FAILED){
            log.error("任务已失败");
            return Result.error("任务已失败");
        }
        Mat mat = null;
        if (task.getCurStepIndex() == 1){
            mat = this.minioService.downloadMat(this.applicationConfiguration.getMatBucketName(),task.getMatFileUrl());
        }else{
            Step lastStep = this.stepService.getByTaskIdAndIndex(task.getId(), task.getCurStepIndex() - 1);
            mat = this.minioService.downloadMat(this.applicationConfiguration.getMatBucketName(),lastStep.getMatFileUrl());
        }
        this.taskService.setStatus(id,Task.RUNNING);
        while (taskService.getTaskStatus(id) == Task.RUNNING){
            if (task.getCurStepIndex() > task.getSize()){
                task.setStatus(Task.FINISHED);
                this.taskService.setStatus(id,Task.FINISHED);
                break;
            }
            Step step = stepService.getByTaskIdAndIndex(task.getId(), task.getCurStepIndex());
            Param param = new Param();
            BeanUtils.copyProperties(step, param);
            mat = AlgorithmStrategyFactory.getAlgorithmExecutor(step.getType(), param).execute(mat);
            String url = this.minioService.uploadMat(this.applicationConfiguration.getMatBucketName(), mat);
            step.setMatFileUrl(url);
            task.setCurStepIndex(task.getCurStepIndex() + 1);
            this.taskService.updateById(task);
            task = this.taskService.getById(id);
        }
        if (task.getStatus() == Task.STOPPED){
            return Result.error("任务已停止");
        }
        return Result.success(mat);
    }

    @PostMapping
    @Transactional
    public Result<Long> create(@RequestBody TaskCreateDTO taskCreateDTO){
        boolean save = taskService.save(taskCreateDTO.getTask());
        if (!save){
            log.error("save task failed");
            return Result.error("save task failed");
        }
        List<Step> steps = taskCreateDTO.getSteps();
        steps.forEach(step -> step.setTaskId(taskCreateDTO.getTask().getId()));
        boolean saveBatch = this.stepService.saveBatch(steps);
        if (!saveBatch){
            log.error("save steps failed");
            this.taskService.removeById(taskCreateDTO.getTask().getId());
            return Result.error("save steps failed");
        }
        return Result.success(taskCreateDTO.getTask().getId());
    }

    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> deleteTaskById(@PathVariable Long id){
        this.taskService.removeById(id);
        this.stepService.lambdaUpdate().eq(Step::getTaskId, id).remove();
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<Task> getById(@PathVariable Long id){
        Task task = this.taskService.getById(id);
        return Result.success(task);
    }

    @GetMapping("/stepsByTaskId/{id}")
    public Result<List<Step>> getStepsByTaskId(@PathVariable Long id){
        List<Step> steps = this.stepService.lambdaQuery().eq(Step::getTaskId, id).list();
        return Result.success(steps);
    }

    @GetMapping("/{objectName}")
    public Result<Mat> getMatFile(@PathVariable String objectName) throws Exception {
        Mat mat = this.minioService.downloadMat(this.applicationConfiguration.getMatBucketName(), objectName);
        return Result.success(mat);
    }

    @GetMapping("/AlgorithmList")
    public Result<List<AlgorithmVO>> getAlgorithmList(){
        return Result.success(AlgorithmTypeEnum.getAlgorithmVos());
    }

}
